import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    // count: sessionStorage.getItem('num')
    count: 0,
    num: 1,
    todos: [
      { id: 1, text: '你好', done: true },
      { id: 2, text: '...', done: false }
    ]
  },
  getters: {
    fn (state) {
      state.num = state.count + 100
      return state.num
    },
    doneTodos (state) {
      // return state.todos.filter(todo => todo.done)
      return 1
    },
    doneTodosCount (state, getters) {
      // return getters.doneTodos.length
      return getters.doneTodos
    },
    gCount (state) {
      return 'xxxxxx'
    }
  },
  mutations: {
    increment (state, { amount: n }) {
      state.count += n
    },
    add (state, amount) {
      state.count += amount
    }
  },
  actions: {
    // incrementAsync ({ commit }, { amount }) {
    //   console.log('amount: ', amount)
    //   setTimeout(() => {
    //     commit('add', amount)
    //   }, 1000)
    // }
    incrementAsync (context, params) {
      // Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象
      // params 是传递过来的参数
      console.log('context: ', context)
      console.log('params: ', params)
      setTimeout(() => {
        context.commit('increment', params)
      }, 1000)
    }
  }
})

export default store
